import 'dart:io';

import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/class_api.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/api/resource_api.dart';
import 'package:FineArt/core/model/class_entity.dart';
import 'package:FineArt/core/model/student_entity.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/page/imageview/FavoritorChooseFolder.dart';
import 'package:FineArt/page/imageview/LargePhotoView.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/platform_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:FineArt/utils/sputils.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

import 'package:extended_image/extended_image.dart';

import 'TeacherCourseView.dart';
import 'RoundCheckBox.dart';

class BookPreview extends StatefulWidget {
  // ignore: non_constant_identifier_names
  static void JumpToPreview(Resource resource, BuildContext context, bool fromFavorite, int page) {
    ResourceApi().resourceDetail(resource.id, resource.type).then((res) {
      if (res.code == 200) {
        if (res.data.type == 0 || res.data.type == 5000) //图书
            {
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return BookPreview(
              resource: resource,
              info: res.data.info,
              fromFavorite: fromFavorite,
              currentPage: page,
            );
          }));
        }
      }
    });
  }

  Resource resource;
  ResourceInfo0 info;
  bool fromFavorite;
  int currentPage;

  BookPreview({this.resource, this.info, this.fromFavorite,this.currentPage});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _BookPreviewState();
  }
}

class _BookPreviewState extends State<BookPreview> {
  int currentIdx;
  var width;
  bool isCheck = false;
  List<ClassEntity> clList = new List();
  List<StudentEntity> stuList = new List();

  String largeImageUrl = "";
  Map cnimage_map = new Map();
  Map class_student_map = new Map(); //班级-学生的map

  ResourceInfo0 bookInfo;

  String pageIndicator="";

  @override
  void initState() {
    // TODO: implement initState
    bookInfo = widget.info;
    currentIdx = widget.currentPage;
    pageIndicator=(currentIdx+1).toString() + "/"+bookInfo.totalpages.toString();
    getClasses();
    getMediumImage();
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  void getClasses() {
    ClassApi().classList().then((res) {
      if (res.code == 200) {
        setState(() {
          clList.clear();
          for (Class c in res.data) {
            ClassEntity entity = new ClassEntity(c.classname, c.classid);
            clList.add(entity);
          }

          if (clList.length > 0) {
            ClassEntity entity = clList[0];
            entity.isCheck = true;
            //请求学生列表
            ClassApi().studentList(entity.id).then((res) {
              if (res.code == 200) {
                List<StudentEntity> ss = [];
                ss.add(StudentEntity("全部", 0, true));
                for (Student s in res.data) {
                  StudentEntity e = new StudentEntity(s.name, s.uid, false);
                  ss.add(e);
                }
                class_student_map[entity.id] = ss;
                setState(() {
                  stuList = ss;
                });
              }
            });
          }
        });
      }
    });
  }

  void getMediumImage() {
    int idx = currentIdx;
    if (cnimage_map.containsKey(idx) &&
        cnimage_map[idx]["medium_image"] != null &&
        cnimage_map[idx]["hdurl"] != null) {
      largeImageUrl = cnimage_map[idx]["hdurl"];
      return;
    }
    if (widget.resource == null) return;
    if (cnimage_map.length > 10) cnimage_map.clear();

    cnimage_map[idx] = new Map();
    cnimage_map[idx]["hdurl"] =
        bookInfo.hdurl + "/" + (idx + 1).toString() + bookInfo.ext;
    largeImageUrl = bookInfo.hdurl + "/" + (idx + 1).toString() + bookInfo.ext;
    setState(() {
      cnimage_map[idx]["medium_image"] = CachedNetworkImage(
        imageUrl: bookInfo.sdurl + "/" + (idx + 1).toString() + bookInfo.ext,
        placeholder: (context, url) =>
            Center(child: CircularProgressIndicator()),
        errorWidget: (context, url, error) => Icon(Icons.error),
      );
    });
  }

  Widget swiperView() {
    return Swiper(
      loop: false,
      index: currentIdx,
      itemBuilder: (context, index) {
        return Container(
            color: Colors.transparent,
            child: cnimage_map[index] == null
                ? null
                : cnimage_map[index]["medium_image"]);
      },
      onTap: (index) {},
      onIndexChanged: (index) {
        currentIdx = index;
        setState(() {
          pageIndicator = (currentIdx + 1).toString() + "/" + bookInfo.totalpages.toString();
        });
        getMediumImage();
      },
      itemCount: bookInfo.totalpages,
    );
  }

  @override
  Widget build(BuildContext context) {
    width = MediaQuery.of(context).size.width;
    var height = MediaQuery.of(context).size.height;
    bool isTeacher = (SPUtils.getRole() == "teacher");
    double item_space = 26;
    return Scaffold(
        backgroundColor: Colors.black,
        body: Container(
          height: height,
          child: SafeArea(
            child: Stack(
              children: [
                Center(child: swiperView()),
                Positioned(
                    top: 10,
                    left: 15,
                    child: InkWell(
                      child: Image.asset("assets/images/arrow_back_white.png"),
                      onTap: () {
                        Navigator.of(context).pop(this);
                      },
                    )),
                Positioned(
                  top: 12,
                  left: width / 2 - 10,
                  child: Text(pageIndicator,
                      style: TextStyle(fontSize: 20, color: Colors.white)),
                ),
                Positioned(
                    bottom: 0,
                    child: Container(
                      width: width,
                      color: Colors.white,
                      padding: EdgeInsets.fromLTRB(16, 5, 10, 5),
                      child: Row(
                        children: [
                          Row(
                            children: [
                              InkWell(
                                onTap: () {
                                  // ToastUtils.toast("高清");
                                  if (Platform.isAndroid) {
                                    PlatformUtil.showHdImage(largeImageUrl);
                                  } else {
                                    LargePhotoView.Jump2LargeView(
                                        largeImageUrl, context);
                                  }
                                },
                                child: Column(
                                  children: [
                                    Image.asset(
                                      "assets/images/icon_highlight.png",
                                      width: 20,
                                      height: 16,
                                    ),
                                    Text(
                                      "高清",
                                      style: TextStyle(
                                          fontSize: 14, color: Colors.black),
                                    )
                                  ],
                                ),
                              ),
                              SizedBox(
                                width: item_space,
                              ),
                            ],
                          ),
                          if (!widget.fromFavorite)Row(
                            children: [
                              InkWell(
                                onTap: () {
                                  // ToastUtils.toast("收藏");
                                  if (isTeacher) {
                                    showFavoriteBottomModel();
                                  } else {
                                    startFavorite();
                                  }
                                },
                                child: Column(
                                  children: [
                                    Image.asset(
                                      "assets/images/icon_fivorite.png",
                                      width: 20,
                                      height: 16,
                                    ),
                                    Text(
                                      "收藏",
                                      style: TextStyle(
                                          fontSize: 14, color: Colors.black),
                                    )
                                  ],
                                ),
                              ),
                              SizedBox(
                                width: item_space,
                              ),
                            ],
                          ),
                          if (isTeacher)
                            Row(
                              children: [
                                InkWell(
                                  onTap: () {
                                    showBottomModel(true);
                                  },
                                  child: Column(
                                    children: [
                                      Image.asset(
                                        "assets/images/icon_jiangjie.png",
                                        width: 20,
                                        height: 16,
                                      ),
                                      Text(
                                        "讲解",
                                        style: TextStyle(
                                            fontSize: 14, color: Colors.black),
                                      )
                                    ],
                                  ),
                                ),
                                SizedBox(
                                  width: item_space,
                                ),
                              ],
                            ),
                          if (isTeacher && false)
                            InkWell(
                              onTap: () {
                                // ToastUtils.toast("带画");
                              },
                              child: Column(
                                children: [
                                  Image.asset(
                                    "assets/images/icon_daihua.png",
                                    width: 20,
                                    height: 16,
                                  ),
                                  Text(
                                    "带画",
                                    style: TextStyle(
                                        fontSize: 14, color: Colors.grey),
                                  )
                                ],
                              ),
                            ),
                          if (isTeacher)
                            Expanded(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    buildRoundText("投送", () {
                                      showBottomModel(false);
                                    }, Colors.white, Colors.red)
                                  ],
                                ))
                        ],
                      ),
                    ))
              ],
            ),
          ),
        ));
  }

  Widget buildRoundText(
      String text, Function press, Color color, Color bgColor) {
    return InkWell(
      onTap: press,
      child: Container(
        decoration: BoxDecoration(
            color: bgColor,
            borderRadius: BorderRadius.all(Radius.circular(25))),
        padding: EdgeInsets.symmetric(vertical: 10, horizontal: 40),
        child: Text(
          text,
          style: TextStyle(color: color, fontSize: 16),
        ),
      ),
    );
  }

  void startShare() {
    if (clList.isEmpty || stuList.isEmpty) {
      ToastUtils.error("获取班级或学生信息错误");
      return;
    }

    int classId = -1;
    for (ClassEntity c in clList) {
      if (c.isCheck) {
        classId = c.id;
        break;
      }
    }

    if (classId == -1) {
      ToastUtils.error("请选择班级和学生");
      return;
    }

    List<String> members = [];
    for (StudentEntity s in stuList) {
      if (!s.isAll && s.isCheck) {
        members.add(s.id.toString());
      }
    }
    if (members.isEmpty) {
      ToastUtils.error("请选择班级和学生");
      return;
    }

    Resource resource = widget.resource;

    ShareBody shareBody = new ShareBody(
        resid: resource.id,
        type: resource.type,
        url: resource.url,
        title: resource.title,
        subitem: currentIdx,
        uids: members);
    ResourceApi().share(shareBody).then((res) {
      if (res.code == 200) {
        ToastUtils.success(res.msg);
      } else {
        ToastUtils.error(res.msg);
      }
    });
  }

  void startCourse() {
    if (largeImageUrl != null && largeImageUrl.isNotEmpty) {
      if (clList.isEmpty || stuList.isEmpty) {
        ToastUtils.error("获取班级或学生信息错误");
        return;
      }

      int classId = -1;
      for (ClassEntity c in clList) {
        if (c.isCheck) {
          classId = c.id;
          break;
        }
      }

      if (classId == -1) {
        ToastUtils.error("请选择班级和学生");
        return;
      }

      List<String> members = [];
      for (StudentEntity s in stuList) {
        if (!s.isAll && s.isCheck) {
          members.add(s.id.toString());
        }
      }
      if (members.isEmpty) {
        ToastUtils.error("请选择班级和学生");
        return;
      }

      CourseBody course = CourseBody(
          members: members,
          id: widget.resource.id,
          type: widget.resource.type,
          subitem: currentIdx,
          layout: 0);
      ClassApi().createCourse(classId, course).then((res) {
        if (res.code == 200) {
          if (Platform.isAndroid) {
            PlatformUtil.startCourse(largeImageUrl, res.data.courseid);
          } else {
            TeacherCourseView.Jump2CourseView(
                largeImageUrl, res.data.courseid, context);
          }
        } else {
          ToastUtils.error(res.msg);
        }
      });
    } else {
      ToastUtils.error("资源错误");
    }
  }

  void showFavoriteBottomModel() {
    showModalBottomSheet(
        context: context,
        isScrollControlled: false,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15), topRight: Radius.circular(15))),
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
                return _buildFavoriteBottom();
              });
        });
  }

  void startFavorite() {
    Resource resource = widget.resource;
    FavoriteReqBody body = new FavoriteReqBody(
        resid: resource.id,
        type: resource.type,
        url: resource.url,
        title: resource.title,
        path: "defalut",
    subitem: currentIdx);
    ResourceApi().favorite(body).then((res) {
      if (res.code == 200) {
        ToastUtils.success(res.msg);
      } else {
        ToastUtils.error(res.msg);
      }
    });
  }

  Widget _buildFavoriteBottom() {
    return SizedBox(
        height: getPortraitSHeight(150.5),
        child: Column(
          children: [
            SizedBox(
              height: getPortraitSHeight(14),
            ),
            Row(
              children: [
                Expanded(
                    child: ColorFiltered(
                      colorFilter: ColorFilter.mode(
                        Colors.white,
                        BlendMode.saturation,
                      ),
                      child: getFavoriteItem(
                          "assets/images/icon_my_material.png", "我的素材", () {
                        LogUtil.d("我的素材 click");
                      }),
                    )),
                Expanded(
                    child: ColorFiltered(
                      colorFilter: ColorFilter.mode(
                        Colors.white,
                        BlendMode.saturation,
                      ),
                      child: getFavoriteItem(
                          "assets/images/icon_school_material.png", "校园素材", () {
                        LogUtil.d("校园素材 click");
                        return;
                        Navigator.of(context).pop();
                        Navigator.of(context)
                            .push(MaterialPageRoute(builder: (context) {
                          return ChooseFolderPage(
                            resource: widget.resource,
                          );
                        }));
                      }),
                    )),
                Expanded(
                    child: getFavoriteItem(
                        "assets/images/icon_my_lesson_prepare.png", "我的备课", () {
                      LogUtil.d("我的备课 click");
                      Navigator.of(context).pop();
                      startFavorite();
                    }))
              ],
            ),
            SizedBox(
              height: getPortraitSHeight(13.5),
            ),
            Divider(
              height: getPortraitSHeight(2),
              thickness: getPortraitSHeight(2),
              color: bg_divider,
            ),
            InkWell(
                child: SizedBox(
                  width: SizeConfig.screenWidth,
                  height: getPortraitSHeight(52),
                  child: Center(
                      child: Text(
                        "取消",
                        style: TextStyle(
                            color: text_black_confirm, fontSize: setSp(18)),
                      )),
                ),
                onTap: () {
                  Navigator.of(context).pop();
                })
          ],
        ));
  }

  Widget getFavoriteItem(String url, String title, Function onTab) {
    return InkWell(
        onTap: onTab,
        child: Column(
          children: [
            Image.asset(
              url,
              width: getPortraitSWidth(48),
              height: getPortraitSHeight(48),
            ),
            SizedBox(
              height: getPortraitSHeight(2),
            ),
            Text(
              title,
              style: TextStyle(fontSize: setSp(13), color: text_black),
            )
          ],
        ));
  }

  void showBottomModel(bool isCasting) {
    showModalBottomSheet(
        context: context,
        isScrollControlled: false,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(15), topRight: Radius.circular(15))),
        builder: (BuildContext context) {
          return StatefulBuilder(
              builder: (BuildContext context, StateSetter setState) {
                return _buildBottomContainer(setState, isCasting);
              });
        });
  }

  Widget _buildClassItem(int index, Function setState) {
    ClassEntity entity = clList[index];
    return Padding(
        padding: EdgeInsets.only(
          left: 10,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
          RoundCheckBox(
              value: entity.isCheck,
              isRadio: true,
              onChanged: (bool val) {
                LogUtil.d("is Check $index $val");
                if (clList[index].isCheck) // radio效果，选中的时候再点击，
                    {
                  setState(() {
                    clList[index].isCheck = true;
                  });

                  return;
                }
                if (val) {
                  setState(() {
                    for (int i = 0; i < clList.length; i++) {
                      bool check = i == index ? true : false;
                      clList[i].isCheck = check;
                    }
                  });
                } else {
                  setState(() {
                    clList[index].isCheck = val;
                  });
                }

                //如果学生列表存在
                if (class_student_map.containsKey(entity.id)) {
                  setState(() {
                    stuList = class_student_map[entity.id];
                  });
                } else {
                  //请求学生列表
                  ClassApi().studentList(entity.id).then((res) {
                    if (res.code == 200) {
                      List<StudentEntity> ss = [];
                      ss.add(StudentEntity("全部", 0, true));
                      for (Student s in res.data) {
                        StudentEntity e =
                        new StudentEntity(s.name, s.uid, false);
                        ss.add(e);
                      }
                      class_student_map[entity.id] = ss;
                      setState(() {
                        stuList = ss;
                      });
                    }
                  });
                }
              }),
          Text(entity.name)
        ]));
  }

  Widget _buildStuItem(int index, Function setState) {
    return Padding(
        padding: EdgeInsets.only(
          left: 10,
        ),
        child: Row(mainAxisAlignment: MainAxisAlignment.start, children: [
          RoundCheckBox(
              value: stuList[index].isCheck,
              onChanged: (bool val) {
                LogUtil.d("is Check $index $val");
                if (index == 0) {
                  for (int i = 0; i < stuList.length; i++) {
                    setState(() {
                      stuList[i].isCheck = val;
                    });
                  }
                } else {
                  setState(() {
                    stuList[index].isCheck = val;
                  });
                }
              }),
          Text(stuList[index].name)
        ]));
  }

  Widget _buildBottomContainer(Function setState, bool isCasting) {
    return Container(
      height: 400, //对话框高度就是此高度
      child: Stack(
        children: [
          Positioned(
              bottom: 52,
              width: width,
              height: 300,
              child: Row(
                children: [
                  Expanded(
                      child: ListView.builder(
                          itemCount: clList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return _buildClassItem(index, setState);
                          })),
                  VerticalDivider(
                    width: 2,
                    color: Colors.blueGrey,
                  ),
                  Expanded(
                      child: ListView.builder(
                          itemCount: stuList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return _buildStuItem(index, setState);
                          })),
                ],
              )),
          Positioned(
              bottom: 50,
              width: width,
              child: Divider(
                color: Colors.grey,
                height: 1,
              )),
          Positioned(
            bottom: 0,
            height: 50,
            width: width,
            child: InkWell(
                onTap: () {
                  if (isCasting) {
                    Navigator.of(context).pop();
                    startCourse();
                  } else {
                    //todo: 分享
                    Navigator.of(context).pop();
                    startShare();
                  }
                },
                child: Center(
                  child: Text("确定"),
                )),
          ),
        ],
      ),
    );
  }
}